package cn.stimd.spring.context.support;

import cn.stimd.spring.beans.BeansException;
import cn.stimd.spring.beans.factory.config.ConfigurableBeanFactory;
import cn.stimd.spring.context.Lifecycle;
import cn.stimd.spring.context.LifecycleProcessor;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class DefaultLifecycleProcessor implements LifecycleProcessor {
    private ConfigurableBeanFactory beanFactory;

    public DefaultLifecycleProcessor(ConfigurableBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }


    @Override
    public void onRefresh() {
        Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
        for (Map.Entry<String, Lifecycle> entry : lifecycleBeans.entrySet()) {
            Lifecycle bean = entry.getValue();
            if(!bean.isRunning()){
                try {
                    bean.start();
                }catch (Exception e){
                    throw new BeansException("Failed to start bean '" + entry.getKey() + "'", e);
                }
            }
        }
    }


    @Override
    public void onClose() {
        Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
        for (Lifecycle lifecycle : lifecycleBeans.values()) {
            lifecycle.stop();
        }
    }


    private Map<String, Lifecycle> getLifecycleBeans() {
        Map<String, Lifecycle> beans = new LinkedHashMap<>();
        List<String> beanNames = this.beanFactory.getBeanNamesForType(Lifecycle.class);
        for (String beanName : beanNames) {
            Lifecycle bean = this.beanFactory.getBean(beanName, Lifecycle.class);
            beans.put(beanName, bean);
        }
        return beans;
    }
}
